using System;
using Volo.Abp;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.Domain.Services;
using Matrix.ServiceDiscovery.Enums;

namespace Matrix.ServiceDiscovery.Entities;

/// <summary>
/// 服务信息实体
/// </summary>
public class ServiceInfo : FullAuditedAggregateRoot<Guid>
{
    /// <summary>
    /// 服务名称
    /// </summary>
    public virtual string Name { get; protected set; } = string.Empty;

    /// <summary>
    /// 服务版本
    /// </summary>
    public virtual string Version { get; protected set; } = string.Empty;

    /// <summary>
    /// 服务描述
    /// </summary>
    public virtual string Description { get; protected set; } = string.Empty;

    /// <summary>
    /// 服务状态
    /// </summary>
    public virtual ServiceStatus Status { get; protected set; }

    /// <summary>
    /// 服务类型
    /// </summary>
    public virtual ServiceType ServiceType { get; protected set; }

    /// <summary>
    /// 服务分组
    /// </summary>
    public virtual string? ServiceGroup { get; protected set; }

    /// <summary>
    /// 负载均衡配置
    /// </summary>
    public virtual LoadBalancingConfig LoadBalancingConfig { get; protected set; } = null!;

    protected ServiceInfo() { }

    public ServiceInfo(
        Guid id,
        string name,
        string version,
        ServiceType serviceType,
        string description = "",
        string? serviceGroup = null) : base(id)
    {
        Name = name;
        Version = version;
        Description = description;
        ServiceType = serviceType;
        ServiceGroup = serviceGroup;
        Status = ServiceStatus.Registered;

        // 创建默认负载均衡配置
        LoadBalancingConfig = new LoadBalancingConfig(
            Guid.NewGuid(),
            id,
            LoadBalancingStrategy.RoundRobin);
    }

    public void Activate()
    {
        Status = ServiceStatus.Running;
    }

    public void Deactivate()
    {
        Status = ServiceStatus.Stopped;
    }

    public void UpdateLoadBalancingStrategy(LoadBalancingStrategy strategy)
    {
        LoadBalancingConfig.UpdateStrategy(strategy);
    }

    public void UpdateLoadBalancingConfig(
        LoadBalancingStrategy? strategy = null,
        bool? enableHealthCheck = null,
        TimeSpan? healthCheckInterval = null,
        int? failureThreshold = null,
        int? successThreshold = null,
        TimeSpan? timeout = null)
    {
        if (strategy.HasValue)
            LoadBalancingConfig.UpdateStrategy(strategy.Value);

        if (enableHealthCheck.HasValue || healthCheckInterval.HasValue ||
            failureThreshold.HasValue || successThreshold.HasValue || timeout.HasValue)
        {
            LoadBalancingConfig.UpdateHealthCheckSettings(
                enableHealthCheck ?? LoadBalancingConfig.EnableHealthCheck,
                healthCheckInterval,
                failureThreshold,
                successThreshold,
                timeout);
        }
    }
}